import React, { useState, useEffect } from 'react';
import { ChevronRight, ChevronDown, ChevronUp, List, X, ArrowUp } from 'lucide-react';

const TableOfContents = ({ content }) => {
  const [headings, setHeadings] = useState([]);
  const [activeId, setActiveId] = useState('');
  const [isCollapsed, setIsCollapsed] = useState(false);
  const [isVisible, setIsVisible] = useState(true);

  useEffect(() => {
    if (!content) return;

    // 解析markdown内容中的标题
    const headingRegex = /^(#{1,6})\s+(.+)$/gm;
    const matches = [];
    let match;

    while ((match = headingRegex.exec(content)) !== null) {
      const level = match[1].length;
      const text = match[2].trim();
      const id = text
        .toLowerCase()
        .replace(/[^\w\u4e00-\u9fff\s-]/g, '')
        .replace(/\s+/g, '-')
        .replace(/^-+|-+$/g, '');

      matches.push({
        id,
        text,
        level
      });
    }

    setHeadings(matches);
  }, [content]);

  useEffect(() => {
    if (headings.length === 0) return;

    // 为页面中的标题添加ID
    const timer = setTimeout(() => {
      headings.forEach(heading => {
        const element = Array.from(document.querySelectorAll('h1, h2, h3, h4, h5, h6'))
          .find(el => el.textContent.trim() === heading.text);
        if (element && !element.id) {
          element.id = heading.id;
        }
      });
    }, 100);

    return () => clearTimeout(timer);
  }, [headings]);

  useEffect(() => {
    if (headings.length === 0) return;

    const observer = new IntersectionObserver(
      (entries) => {
        entries.forEach((entry) => {
          if (entry.isIntersecting) {
            setActiveId(entry.target.id);
          }
        });
      },
      {
        rootMargin: '-20% 0% -35% 0%',
        threshold: 0
      }
    );

    headings.forEach(heading => {
      const element = document.getElementById(heading.id);
      if (element) {
        observer.observe(element);
      }
    });

    return () => observer.disconnect();
  }, [headings]);

  const scrollToHeading = (id) => {
    const element = document.getElementById(id);
    if (element) {
      const offset = 100;
      const elementPosition = element.offsetTop - offset;
      window.scrollTo({
        top: elementPosition,
        behavior: 'smooth'
      });
    }
  };

  if (headings.length === 0) return null;

  return (
    <>
      {/* 悬浮目录和回到顶部按钮 */}
      <div className="fixed right-4 top-1/2 transform -translate-y-1/2 z-50 flex flex-col items-end space-y-4">
        {/* 目录面板 */}
        {isVisible && (
          <div className="bg-white dark:bg-gray-800 rounded-xl shadow-2xl border border-gray-200 dark:border-gray-700 max-w-xs w-80 max-h-96 overflow-hidden animate-scale-in">
            {/* 目录标题 */}
            <div className="flex items-center justify-between p-4 border-b border-gray-200 dark:border-gray-700 bg-gray-50 dark:bg-gray-700/50">
              <div className="flex items-center space-x-2">
                <List className="h-5 w-5" style={{ color: 'var(--color-primary)' }} />
                <h3 className="font-semibold text-gray-900 dark:text-white text-sm">目录</h3>
              </div>
              <div className="flex items-center space-x-1">
                <button
                  onClick={() => setIsCollapsed(!isCollapsed)}
                  className="p-1 rounded-md hover:bg-gray-200 dark:hover:bg-gray-600 transition-all duration-300 hover:scale-110"
                  aria-label={isCollapsed ? '展开目录' : '收起目录'}
                >
                  {isCollapsed ? (
                    <ChevronDown className="h-4 w-4 text-gray-500 dark:text-gray-400 transition-transform duration-300" />
                  ) : (
                    <ChevronUp className="h-4 w-4 text-gray-500 dark:text-gray-400 transition-transform duration-300" />
                  )}
                </button>
                <button
                  onClick={() => setIsVisible(false)}
                  className="p-1 rounded-md hover:bg-gray-200 dark:hover:bg-gray-600 transition-all duration-300 hover:scale-110 icon-spin"
                  aria-label="隐藏目录"
                >
                  <X className="h-4 w-4 text-gray-500 dark:text-gray-400" />
                </button>
              </div>
            </div>

            {/* 目录内容 */}
            {!isCollapsed && (
              <nav className="p-3 max-h-80 overflow-y-auto toc-scroll">
                <ul className="space-y-1">
                  {headings.map((heading, index) => (
                    <li key={index}>
                      <button
                        onClick={() => scrollToHeading(heading.id)}
                        className={`w-full text-left px-2 py-1.5 rounded-md text-xs transition-all duration-300 hover:bg-gray-100 dark:hover:bg-gray-700 hover:scale-105 ${
                          activeId === heading.id
                            ? 'border-l-2 animate-glow'
                            : 'text-gray-600 dark:text-gray-400 hover:text-gray-900 dark:hover:text-gray-200'
                        }`}
                        style={activeId === heading.id ? {
                          backgroundColor: 'var(--color-primary-light)',
                          color: 'var(--color-primary-dark)',
                          borderLeftColor: 'var(--color-primary)',
                          paddingLeft: `${(heading.level - 1) * 8 + 8}px`
                        } : {
                          paddingLeft: `${(heading.level - 1) * 8 + 8}px`
                        }}
                      >
                        <span className="block truncate" title={heading.text}>
                          {heading.text}
                        </span>
                      </button>
                    </li>
                  ))}
                </ul>
              </nav>
            )}
          </div>
        )}

        {/* 控制按钮组 */}
        <div className="flex flex-col space-y-2">
        {/* 显示/隐藏目录按钮 */}
        {!isVisible && (
          <button
            onClick={() => setIsVisible(true)}
            className="w-12 h-12 bg-white dark:bg-gray-800 border border-gray-200 dark:border-gray-700 rounded-full shadow-lg hover:shadow-xl transition-all duration-300 flex items-center justify-center group hover:scale-110 animate-pulse"
            aria-label="显示目录"
          >
            <List className="h-5 w-5 text-gray-600 dark:text-gray-400 transition-all duration-300 group-hover:theme-color icon-bounce" />
          </button>
        )}

        {/* 回到顶部按钮 */}
        <button
          onClick={() => window.scrollTo({ top: 0, behavior: 'smooth' })}
          className="w-12 h-12 text-white rounded-full transition-all duration-300 shadow-lg hover:shadow-xl flex items-center justify-center group theme-gradient hover:scale-110 animate-float"
          aria-label="回到顶部"
        >
          <ArrowUp className="h-5 w-5 transition-all duration-300 group-hover:-translate-y-1 group-hover:animate-bounce" />
        </button>
        </div>
      </div>
    </>
  );
};

export default TableOfContents;
